window.onload = () => {
   LoadData();
   generateMalware();
   createConnections();
   updateConnections();
   setMalwareVisibility();

   getElement("packet-count").innerHTML = formatFloat(parseFloat(getCookie("packets")), 2);

   getElement("return-button").addEventListener("click", () => {
      window.location = "../index.html";
   });
}
var resizeList = [];
window.onresize = () => {
   scaleAllMalware();
}


function findParent(popup) {
   let parentMalware;
   for (const parent of Object.values(popupData)) {
      if (parent.id === popup.from) {
         parentMalware = parent;
         break;
      }
   }
   return parentMalware;
}
function scaleAllMalware() {
   for (const object of resizeList) {
      // Make sure the object is visible
      for (const malware of Object.values(popupData)) {
         if (getElement(malware.name) == object.start && !getElement(malware.name).classList.contains("hidden")) {
            scaleConnection(object.line, object.start, object.end);
         }
      }
   }
}
function generateMalware() {
   for (const popup of Object.values(popupData)) createMalware(popup);
}
function createMalware(popup) {
   const malware = getElement("malware-template").cloneNode(true);
   document.body.appendChild(malware);
   malware.classList.remove("hidden");
   if (popup.unlocked) malware.classList.add("unlocked");
   malware.id = popup.name;

   malware.querySelector(".malware-title").innerHTML = popup.name;

   malware.style.top = `${50 + popup.display.top}vh`;
   malware.style.left = `${50 + popup.display.left}vw`;

   malwareClickEvents(popup, malware);
   createMalwareTooltips(popup, malware)
}
function malwareClickEvents(popup, malware) {
   // BUY MALWARE
   malware.addEventListener("click", () => {
      if (popup.unlocked) return;

      const packets = parseFloat(getCookie("packets"));
      if (packets < popup.stats.cost) {
         return;
      }

      const newPackets = packets - popup.stats.cost;
      setCookie("packets", newPackets, 31);
      getElement("packet-count").innerHTML = formatFloat(newPackets, 2);

      popup.unlocked = true;
      malware.classList.add("unlocked");

      createCode(malware.getBoundingClientRect(), randomInt(20, 25, true));
      
      setMalwareVisibility();
      scaleAllMalware();
      // updateMalwareCookie();
      cookies.unlockedMalware.update();
      updateConnections();
   });
}
// function updateMalwareCookie() {
//    let newCookie = "";
//    for (const popup of Object.values(popupData)) newCookie += popup.unlocked ? "1" : "0";
//    setCookie("unlockedMalware", newCookie, 31);
// }
function createMalwareTooltips(popup, malware) {
   malware.addEventListener("mouseover", () => {
      const tooltips = getElement("tooltips");
      tooltips.classList.remove("hidden");

      // Position the tooltips
      const bounds = malware.getBoundingClientRect();
      tooltips.style.left = `${bounds.x + bounds.width / 2}px`;
      tooltips.style.top = `${bounds.y}px`;

      if (popup.unlocked) {
         getElement("tooltips-cost-img").classList.add("hidden");
         getElement("tooltips").classList.add("selected");
      } else {
         getElement("tooltips-cost-img").classList.remove("hidden");
         getElement("tooltips").classList.remove("selected");
      }

      if (popup.stats.points === undefined || !popup.unlocked) {
         getElement("tooltips-points").innerHTML = "";
      } else {
         if (typeof popup.stats.points == "object") {
            getElement("tooltips-points").innerHTML = "+" + popup.stats.points.min + "-" + popup.stats.points.max + " points";
         } else {
            getElement("tooltips-points").innerHTML = "+" + popup.stats.points + " point" + (popup.stats.points == 1 ? "" : "s");
            getElement("tooltips-points").innerHTML = `${popup.stats.points >= 0 ? "+" : ""}${popup.stats.points} point${popup.stats.points == 1 ? "" : "s"}`;
         }
      }

      getElement("tooltips-name").innerHTML = popup.name;
      getElement("tooltips-cost-img").innerHTML = popup.stats.cost;
      getElement("tooltips-unlock-type").innerHTML = popup.unlocked ? "(UNLOCKED)" : "(LOCKED)";
      getElement("tooltips-special").innerHTML = popup.stats.special;
      getElement("tooltips-description").innerHTML = popup.stats.description;
   });
   malware.addEventListener("mouseout", () => {
      getElement("tooltips").classList.add("hidden");
   });
}

function createConnections() {
   for (const popup of Object.values(popupData)) {
      // Stop if there is no connection to be made.
      if (popup.from !== undefined) {
         const malware = getElement(popup.name);

         let parentMalware;
         for (const parent of Object.values(popupData)) {
            if (parent.id === popup.from) {
               parentMalware = getElement(parent.name);
               break;
            }
         }

         createConnection(malware, parentMalware, popup.name);
      }
   }
}
function updateConnections() {
   for (const connection of document.getElementsByClassName("connection")) {
      if (getElement(connection.id.replace("-connection", "")).classList.contains("unlocked")) {
         connection.classList.add("unlocked");
      }
   }
}
function scaleConnection(line, startObj, endObj) {
   // Scale line length
   const start = startObj.getBoundingClientRect();
   const end = endObj.getBoundingClientRect();
   const a2 = Math.pow(start.x - end.x, 2);
   const b2 = Math.pow(start.y - end.y, 2);
   const distance = Math.sqrt(a2 + b2);
   line.style.width = `${distance}px`;

   // Find angle between malware
   const angleRadians = Math.atan2(end.y - start.y, end.x - start.x);
   const angleDeg = angleRadians * 180 / Math.PI;
   line.style.transform = `translateY(-50%) rotate(${angleDeg}deg)`;
}
function createConnection(startObj, endObj, name) {
   const start = startObj.getBoundingClientRect();
   const line = document.createElement("div");
   getElement("connection-container").appendChild(line);
   line.classList.add("connection");
   line.id = `${name}-connection`;

   scaleConnection(line, startObj, endObj);
   resizeList.push({ line: line, start: startObj, end: endObj });

   const scaleTop = scalePX(start.y + start.height / 2, "vh");
   line.style.top = `${scaleTop}vh`;

   const scaleLeft = scalePX(start.x + start.width / 2, "vw");
   line.style.left = `${scaleLeft}vw`;
}

function setMalwareVisibility() {
   // Hide if it is locked and its from is unlocked
   for (const popup of Object.values(popupData)) {
      const parentMalware = findParent(popup);

      if (popup.from !== undefined && !popup.unlocked && !parentMalware.unlocked) {
         getElement(popup.name).classList.add("hidden");
         getElement(`${popup.name}-connection`).classList.add("hidden");
      } else if (popup.from !== undefined) {
         getElement(popup.name).classList.remove("hidden");
         getElement(`${popup.name}-connection`).classList.remove("hidden");
      }
   }
}

const codeList = [];
let codeInterval;
function startCodeCheck() {
   codeInterval = setInterval(() => {
      for (const code of codeList) {
         code.tick();
      }
   }, 30);
}
function createCode(startPos, codeN) {
   const codeContainer = document.createDocumentFragment();
   for (let i = 0; i < codeN; i++) {
      const code = new Code(startPos);
      codeContainer.appendChild(code.displayObj);

      if (codeList.length === 1) startCodeCheck();
   }
   document.body.appendChild(codeContainer);
}
class Code {
   constructor(startPos) {
      this.displayObj = document.createElement("div");
      this.displayObj.classList.add("code")
      if (Math.random() < 0.35) this.displayObj.classList.add("red");

      this.displayObj.innerHTML = this.randomCharacter();

      this.startX = startPos.x + startPos.width/2;
      this.startY = startPos.y + startPos.height/2;

      this.left = 0;
      this.top = 0;
      this.life = 0;
      this.leftVel = getCurve() * randomSign();
      this.topVel = getCurve() * randomSign();

      this.dieTime = randomInt(17, 25, true);

      codeList.push(this);
   }
   randomCharacter() {
      const characters = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")"];
      return characters[randomInt(0, characters.length)];
   }
   tick() {
      if (this.life % 1.5 == 0) {
         this.displayObj.innerHTML = this.randomCharacter();
      }
      this.left += this.leftVel * 3;
      this.top += this.topVel * 3;

      this.displayObj.style.left = this.startX + this.left + "px";
      this.displayObj.style.top = this.startY + this.top + "px";
      this.displayObj.style.opacity = 1 - this.life / this.dieTime;

      if (this.life++ >= this.dieTime) {
         this.displayObj.remove();
         codeList.splice(codeList.indexOf(this), 1);

         if (codeList.length < 1) clearInterval(codeInterval);
      }
   }
}